package com.xfcycle.zebrabikegp.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.util.PermissionsCheckerUtil;

/**
 * 权限窗体
 * <p>
 * Created by xFcycle on 2017/5/27.
 */

public class PermissionsActivity extends AppCompatActivity {
    private static final String TAG = "PermissionsActivity";

    //权限请求被通过
    public static final int PERMISSIONS_GRANTED = 0;
    //权限请求被拒绝
    public static final int PERMISSIONS_DENIED = 1;

    //系统权限管理页面参数
    private static final int PERMISSION_REQUEST_CODE = 0;
    //权限参数
    private static final String EXTRA_PERMISSION = "zebra.permission.extra_permission";

    //方案
    private static final String PACKAGE_URL_SCHEME = "package";

    //权限检测工具类
    private PermissionsCheckerUtil mPermissionsCheckerUtil;
    //是否需要系统权限检测
    private boolean isRequireCheck;

    //启动当前页面的公开接口
    public static void startActivityForResult(Activity activity, int requestCode, String[] permissions) {
        Intent intent = new Intent(activity, PermissionsActivity.class);
        intent.putExtra(EXTRA_PERMISSION, permissions);
        ActivityCompat.startActivityForResult(activity, intent, requestCode, null);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (null == getIntent() || !getIntent().hasExtra(EXTRA_PERMISSION)) {
            Log.e(TAG, "onCreate: 无法获取传递过来的权限列表");
        }
        setContentView(R.layout.activity_text);

        mPermissionsCheckerUtil = new PermissionsCheckerUtil(this);
        isRequireCheck = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRequireCheck) {
            String[] permissions = getPermissions();
            if (mPermissionsCheckerUtil.judgePermissionListDenied(permissions)) {
                //请求权限
                requestPermissions(permissions);
            } else {
                //全部权限都已获取
                allPermissionsGranted();
            }
            return;
        }
        isRequireCheck = !isRequireCheck;
    }

    /**
     * 获取权限列表
     *
     * @return 通过Bundle获得的权限列表
     */
    private String[] getPermissions() {
        return null == getIntent() ? null : getIntent().getStringArrayExtra(EXTRA_PERMISSION);
    }

    /**
     * 请求权限兼容低版本
     *
     * @param permissions 权限列表
     */
    private void requestPermissions(String[] permissions) {
        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

    /**
     * 全部的请求权限都已获取
     */
    private void allPermissionsGranted() {
        setResult(PERMISSIONS_GRANTED);
        finish();
    }

    /**
     * 用户权限处理
     * 如果所需权限已全部获取，则直接跳过
     * 若未全部获取，则跳出提示dialog
     * @param requestCode 请求码
     * @param permissions 权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
            isRequireCheck = true;
            //所有权限都已获取
            allPermissionsGranted();
            return;
        } else {
            isRequireCheck = false;
            //展示未获取权限Dialog
            showMissingPermissionDialog();
        }
    }

    /**
     * 判断是否已拥有所有权限
     * @param grantResults 申请权限结果集
     * @return 返回判断权限
     */
    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示缺失权限提示
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
        builder.setTitle("帮助");
        builder.setMessage("123");

        //退出设置权限，直接退出应用
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setResult(PERMISSIONS_DENIED);
                finish();
            }
        });

        //用户自己设置权限
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });
    }

    /**
     * 跳转到设置应用权限的系统setting页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }
}
